<script setup>

import {ref} from "vue";
import {showToast} from "vant";
import {register} from "@/api/request.js";
import {useUserStore} from "@/store/user.js";
import router from "@/router/index.js";

const username = ref('')
const password = ref('')
const confirmPassword = ref('')
const phone = ref('')

const store = useUserStore()
const onClickLeft = () => {
  history.back()
}

const handleSubmit = () => {
  if (password.value !== confirmPassword.value) {
    showToast('密码不匹配')
    return false
  }

  register({
    username: username.value,
    password: password.value,
    phone: phone.value
  }).then(res => {
    if (res.status === 200) {
      showToast('注册成功')

      const user = res.data.data

      store.userId = user.id
      store.username = user.username
      store.avatar = user.avatar
      store.isAuthenticated = true

      router.push('/')
    }else {
      showToast(res.data.message)
    }
  })
}
</script>

<template>
  <van-nav-bar left-arrow @click-left="onClickLeft"/>

  <div class="register-box">
    <div class="register-content">
      <van-nav-bar>
        <template #title>
          <div class="title">注册</div>
        </template>
      </van-nav-bar>
      <van-form @submit="handleSubmit">
        <van-field v-model="username" label="用户名" required></van-field>
        <van-field v-model="password" label="密码" required type="password"></van-field>
        <van-field v-model="confirmPassword" label="确认密码" required type="password"></van-field>
        <van-field v-model="phone" label="手机号" required></van-field>
        <div style="margin-top: 1rem">
          <van-button block native-type="submit" type="primary">注册</van-button>
        </div>
      </van-form>
    </div>

  </div>

</template>

<style lang="less" scoped>
.register-box {
  width: 100%;
  height: 80vh;
  display: flex;
  overflow: hidden;
  background-repeat: no-repeat;
  background-size: cover;
  opacity: 0.9;

  .register-content {
    margin: auto;
    padding: 10px 10px 20px 10px;
    background-color: #fff;
    border-radius: 10px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    opacity: 0.9;

    .title {
      font-size: 20px;
      font-weight: 600;
    }
  }
}
</style>